<?php
/*
	本插件：$this->model('model')->方法名();
	其他地方调用：model('jy_h5live/douyu')->方法名();
	https://open.douyu.com/source/api/37
*/
namespace jy_h5live;
defined('BY_JYA') or exit('error');
class douyu extends \plugin{
	public function __construct($setting=array()){
        parent::__construct('jy_h5live');
		$setting=$this->plugin_setting('basic');
        if(!$setting['douyu_aid'] || !$setting['douyu_key']){
            exi('基本设置--直播接口--斗鱼的身份标识，身份密钥都必须填写','error');
        }
        $this->config=array(
            'douyu_aid'=>$setting['douyu_aid'],
            'douyu_key'=>$setting['douyu_key'],
			'douyu_token'=>$setting['douyu_token'],
			'douyu_expire'=>$setting['douyu_expire'],
        );
		if(!$setting['douyu_expire'] || $setting['douyu_expire']<=TIMESTAMP){
			$this->gettoken();
		}
    }
	/**
     * 获取token
     */
	public function gettoken(){
		$get=array(
			'aid'=>$this->config['douyu_aid'],
			'time'=>TIMESTAMP,
		);
		$auth=$this->getauth($get,'/api/thirdPart/token');
		$url='https://openapi.douyu.com/api/thirdPart/token?aid='.$this->config['douyu_aid'].'&time='.TIMESTAMP.'&auth='.$auth;
		$res=$this->request($url);
		if($res['code']){
			exi('获取token失败，失败原因:'.$res['code'].$res['msg'],'error');
		}
		$res=$res['data'];
		if($res['token']){
			$this->config['douyu_token']=$res['token'];
			$this->config['douyu_expire']=$res['expire']-100;
			$basic=$this->plugin_setting('basic');
			$basic['douyu_token']=$res['token'];
			$basic['douyu_expire']=$res['expire']-100;
			$this->plugin_setting('basic',$basic);
		}
		return $res['token'];
	}
	public function gethls_url($rid=''){
		$get=array(
			'aid'=>$this->config['douyu_aid'],
			'token'=>$this->config['douyu_token'],
			'time'=>TIMESTAMP,
		);
		$auth=$this->getauth($get,'/api/thirdPart/getPlay');
		$url='https://openapi.douyu.com/api/thirdPart/token?aid='.$get['aid'].'&time='.TIMESTAMP.'&token='.$get['token'].'&auth='.$auth;
		$post=array(
			'rid'=>$rid,
		);
		$res=$this->request($url,$post);
		if($res['code']){
			exi('获取直播视频流失败，失败原因:'.$res['code'].$res['msg'],'error');
		}
		$res=$res['data'];
		return $res;
	}
	public function request($url,$post=array(),$continue=true,$direct=false,$return_error=false,$isjson=false,$isrequest=false){
		$post=ijson_encode($post);
		//file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . $url." request记录:" . $post."\r\n", FILE_APPEND);
		$rurl=$url;
		if($isjson){
			$headers = array('Content-Type' => 'application/json');
			$result=cfc('http')->ihttp_json($rurl,$post);
		}elseif($isrequest){
			$result=cfc('http')->ihttp_request($rurl,$post);
		}elseif($post){
			$result=cfc('http')->ihttp_post($rurl,$post);
		}else{
			$result=cfc('http')->ihttp_get($rurl);
		}
		if(is_error($result)){			
			$message="斗鱼接口错误, 错误: {$result['message']}";
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		$data=preg_replace('/[\x00-\x1F]/','',$result['content']);
		$data=@json_decode($data,true);
		if($data['errcode']){
			$message=$this->error_code($data['errcode']).' '.$data['errmsg'].' '.$data['errcode'];
			if($return_error || $_SESSION['this']=='custom'){
				//return error($message);
			}else{
				//exi($message,'error');
			}
		}
		if($direct){
			return $result;
		}
		if(!is_array($data) || !$data){
			if($result['content']=='404'){
				$message='请设置白名单！斗鱼管理中心-开发管理-服务配置-IP白名单设置栏';
			}else{
				$message='斗鱼接口错误，以下为原始数据：'.$result['content'];
			}
    		if($return_error){
    			return error($message);
    		}else{
    			exi($message,'error');
    		}
		}
		return $data;
	}
	public function getauth($params=array(),$atcion='') {
		$douyu_key=$this->config['douyu_key'];
		ksort($params); // 按键名对参数数组进行排序
        $stringToBeSigned = $atcion."?";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === empty($v) && "@" != substr($v, 0, 1)) {
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }
		$stringToBeSigned .=$douyu_key;
        $signatureContent = str_replace('\/', '/', $stringToBeSigned);
		$auth=md5($signatureContent);
		return $auth;
    }
}
?>